﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.security;
using System.Security.Cryptography.X509Certificates;
using System.IO;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

using HisGL.CA;
using HisGL.Core;
using HisGL.Json;
using HisGL.Crypto;
using System.Xml.Linq;

namespace TestCAPdfPro
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string src = @"D:\Test.pdf"; // 原始带签名的 PDF 文件路径
            string dest = @"D:\Test.pdf_signed_1.pdf"; // 修改后的 PDF 文件路径
            string password = "password"; // 打开 PDF 文件的密码（如果有的话）
            string newText = "这是新增的文本。"; // 要添加的文本内容

            using (FileStream fs = new FileStream(src, FileMode.Open, FileAccess.Read))
            {
                PdfReader reader = new PdfReader(fs);
                using (FileStream stamped = new FileStream(dest, FileMode.Create))
                {
                    PdfStamper stamper = new PdfStamper(reader, stamped,'\0',true);
                    PdfContentByte over = stamper.GetOverContent(1);
                    over.BeginText();
                    BaseFont bf = BaseFont.CreateFont();

                    over.SetFontAndSize(bf,20);
                    over.SetColorFill(BaseColor.BLUE);
                    over.SetTextMatrix(50, 100);
                    over.ShowText("这是新添加的内容这是新添加的内容这是新添加的内容");
                    //over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "这是新添加的内容", 300, 20, 0);
                    over.EndText();

                    iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(100, 200, 400,300 );
                    PdfFormField sign = PdfFormField.CreateSignature(stamper.Writer);
                    sign.SetWidget(rect, PdfAnnotation.HIGHLIGHT_INVERT);
                    sign.FieldName = "sig1";
                    stamper.AddAnnotation(sign, 1); 
                     rect = new iTextSharp.text.Rectangle(100, 400, 400, 500);
                    sign = PdfFormField.CreateSignature(stamper.Writer);
                    sign.SetWidget(rect, PdfAnnotation.HIGHLIGHT_INVERT);
                    sign.FieldName = "sig2";
                    stamper.AddAnnotation(sign, 1);

                    stamper.Close();
                }
                reader.Close(); // 最后关闭 PdfReader，这将确保所有的更改都被写入到输出流中
            }           //
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ReqCALogin reqLogin = new ReqCALogin();
            reqLogin.UserUid = "4238";
            reqLogin.UserPin = "123456";

            UserInfo UserInfo = new UserInfo();

            ResCA<CALoginInfo> resCALogin = CAManager.Instance.CALogin(UserInfo, reqLogin);
            if (resCALogin.Code >= 0)
            {
                //resCALogin.Data.UserUid, resCALogin.Data.UserToken
                ReqCASignPdf reqCAPdf = new ReqCASignPdf();
                reqCAPdf.ApplicationId = reqLogin.ApplicationId;
                reqCAPdf.UserToken = resCALogin.Data.UserToken;
                reqCAPdf.FilePath = @"D:\Test.pdf";

                reqCAPdf.Height = 100;
                reqCAPdf.Width = 100;
                reqCAPdf.X = 0;
                reqCAPdf.Y = 0;
                reqCAPdf.Page = 1;

                reqCAPdf.UseFieldText = false;
                reqCAPdf.FieldText = "";
                reqCAPdf.FieldName = "";

                ResCA<CASignPdf> resCAPdf= CAManager.Instance.CASignPdf(UserInfo, reqCAPdf);
                if(resCAPdf.Code >= 0)
                {
                    //Convert.ToByte
                    byte[] DocBytes = Convert.FromBase64String(resCAPdf.Data.SignedPDFBase64);
                    FileStream fs = new FileStream(reqCAPdf.FilePath+"_signed.pdf", FileMode.CreateNew);
                    BinaryWriter bw = new BinaryWriter(fs);
                    bw.Write(DocBytes, 0, DocBytes.Length);
                    bw.Close();
                    fs.Close();
                }

            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //
            ReqCALogin reqLogin = new ReqCALogin();
            reqLogin.UserUid = "4238";
            reqLogin.UserPin = "123456";

            UserInfo UserInfo = new UserInfo();

            ResCA<CALoginInfo> resCALogin = CAManager.Instance.CALogin(UserInfo, reqLogin);
            if (resCALogin.Code >= 0)
            {
                //resCALogin.Data.UserUid, resCALogin.Data.UserToken
                ReqCASignPdf reqCAPdf = new ReqCASignPdf();
                reqCAPdf.ApplicationId = reqLogin.ApplicationId;
                reqCAPdf.UserToken = resCALogin.Data.UserToken;
                reqCAPdf.FilePath = @"D:\Test.pdf_signed_1.pdf";

                reqCAPdf.Height = 100;
                reqCAPdf.Width = 100;
                reqCAPdf.X = 0;
                reqCAPdf.Y = 0;
                reqCAPdf.Page = 1;
                reqCAPdf.UseTimestamp = true;

                reqCAPdf.UseFieldText = true;
                reqCAPdf.FieldText = "ererer";
                reqCAPdf.FieldName = "sig1";

                ResCA<CASignPdf> resCAPdf = CAManager.Instance.CASignPdf(UserInfo, reqCAPdf);
                if (resCAPdf.Code >= 0)
                {
                    //Convert.ToByte
                    byte[] DocBytes = Convert.FromBase64String(resCAPdf.Data.SignedPDFBase64);
                    FileStream fs = new FileStream(reqCAPdf.FilePath + "_signed.pdf", FileMode.Create);
                    BinaryWriter bw = new BinaryWriter(fs);
                    bw.Write(DocBytes, 0, DocBytes.Length);
                    bw.Close();
                    fs.Close();
                }

                reqCAPdf.FilePath = @"D:\Test.pdf_signed_1.pdf_signed.pdf";
                reqCAPdf.UseFieldText = true;
                reqCAPdf.FieldText = "e2";
                reqCAPdf.FieldName = "sig2";

                resCAPdf = CAManager.Instance.CASignPdf(UserInfo, reqCAPdf);
                if (resCAPdf.Code >= 0)
                {
                    //Convert.ToByte
                    byte[] DocBytes = Convert.FromBase64String(resCAPdf.Data.SignedPDFBase64);
                    FileStream fs = new FileStream(reqCAPdf.FilePath + "_signed.pdf", FileMode.Create);
                    BinaryWriter bw = new BinaryWriter(fs);
                    bw.Write(DocBytes, 0, DocBytes.Length);
                    bw.Close();
                    fs.Close();
                }

            }
        }

    private void button4_Click(object sender, EventArgs e)
    {
      //
      string src = @"D:\Test.pdf"; // 原始带签名的 PDF 文件路径
      string dest = @"D:\Test_1.pdf"; // 修改后的 PDF 文件路径

      using (PdfReader reader = new PdfReader(src))
      using (FileStream fs = new FileStream(dest, FileMode.Create))
      {
        // 允许增量更新（关键！为后续签名预留空间）
        //PdfStamper stamper = PdfStamper.CreateSignature(reader, fs, '\0', null, true);
        PdfStamper stamper = new PdfStamper(reader, fs, '\0', true);

        //FontFactory.RegisterDirectory(@"C:\Windows\Fonts");

        PdfContentByte overContent = stamper.GetOverContent(1);
        overContent.BeginText();
        overContent.SetFontAndSize(BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED), 12);
        overContent.SetTextMatrix(100, reader.GetPageSize(1).Height - 50);
        overContent.ShowText("【新增内容】" + "第一次签名附加文字！");
        overContent.EndText();

        //设置签名域1
        //PdfSignatureAppearance appearance = stamper.SignatureAppearance;
        iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(100, reader.GetPageSize(1).Height - 100, 150, reader.GetPageSize(1).Height - 130);
        PdfFormField sign = PdfFormField.CreateSignature(stamper.Writer);
        sign.SetWidget(rect, PdfAnnotation.HIGHLIGHT_INVERT);
        sign.FieldName = "sig1";
        stamper.AddAnnotation(sign, 1);

        stamper.Close();

/*
        rect = new iTextSharp.text.Rectangle(100, 400, 400, 500);
        sign = PdfFormField.CreateSignature(stamper.Writer);
        sign.SetWidget(rect, PdfAnnotation.HIGHLIGHT_INVERT);
        sign.FieldName = "sig2";
        stamper.AddAnnotation(sign, 1);
*/
        
      }

      //签名
      ReqCALogin reqLogin = new ReqCALogin();
      reqLogin.UserUid = "4238";
      reqLogin.UserPin = "123456";

      UserInfo UserInfo = new UserInfo();
      ReqCASignPdf reqCAPdf = new ReqCASignPdf();
      ResCA<CASignPdf> resCAPdf;

      ResCA <CALoginInfo> resCALogin = CAManager.Instance.CALogin(UserInfo, reqLogin);
      if (resCALogin.Code >= 0)
      {
        //resCALogin.Data.UserUid, resCALogin.Data.UserToken
        
        reqCAPdf.ApplicationId = reqLogin.ApplicationId;
        reqCAPdf.UserToken = resCALogin.Data.UserToken;
        reqCAPdf.FilePath = dest;

        reqCAPdf.Height = 100;
        reqCAPdf.Width = 100;
        reqCAPdf.X = 0;
        reqCAPdf.Y = 0;
        reqCAPdf.Page = 1;
        reqCAPdf.UseTimestamp = true;

        reqCAPdf.UseFieldText = true;
        reqCAPdf.FieldText = "第一次签名";
        reqCAPdf.FieldName = "sig1";

        resCAPdf = CAManager.Instance.CASignPdf(UserInfo, reqCAPdf);
        if (resCAPdf.Code >= 0)
        {
          //Convert.ToByte
          byte[] DocBytes = Convert.FromBase64String(resCAPdf.Data.SignedPDFBase64);
          FileStream fs = new FileStream(reqCAPdf.FilePath + "_signed.pdf", FileMode.Create);
          BinaryWriter bw = new BinaryWriter(fs);
          bw.Write(DocBytes, 0, DocBytes.Length);
          bw.Close();
          fs.Close();
        }


      }

      //第二次增加内容
      src = @"D:\Test_1.pdf_signed.pdf"; // 原始带签名的 PDF 文件路径
      dest = @"D:\Test_2.pdf"; // 修改后的 PDF 文件路径

      using (PdfReader reader = new PdfReader(src))
      using (FileStream fs = new FileStream(dest, FileMode.Create))
      {
        // 允许增量更新（关键！为后续签名预留空间）
        //PdfStamper stamper = PdfStamper.CreateSignature(reader, fs, '\0', null, true);
        PdfStamper stamper = new PdfStamper(reader, fs, '\0', true);

        //FontFactory.RegisterDirectory(@"C:\Windows\Fonts");

        PdfContentByte overContent = stamper.GetOverContent(1);
        overContent.BeginText();
        overContent.SetFontAndSize(BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED), 12);
        overContent.SetTextMatrix(100, reader.GetPageSize(1).Height - 250);
        overContent.ShowText("【新增内容】" + "第二次签名附加文字！");
        overContent.EndText();

        //设置签名域1
        //PdfSignatureAppearance appearance = stamper.SignatureAppearance;
        iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(100, reader.GetPageSize(1).Height - 300, 150, reader.GetPageSize(1).Height - 330);
        PdfFormField sign = PdfFormField.CreateSignature(stamper.Writer);
        sign.SetWidget(rect, PdfAnnotation.HIGHLIGHT_INVERT);
        sign.FieldName = "sig2";
        stamper.AddAnnotation(sign, 1);

        stamper.Close();

      }

      reqCAPdf.ApplicationId = reqLogin.ApplicationId;
      reqCAPdf.UserToken = resCALogin.Data.UserToken;
      reqCAPdf.FilePath = dest;

      reqCAPdf.Height = 100;
      reqCAPdf.Width = 100;
      reqCAPdf.X = 0;
      reqCAPdf.Y = 0;
      reqCAPdf.Page = 1;
      reqCAPdf.UseTimestamp = true;

      reqCAPdf.UseFieldText = true;
      reqCAPdf.FieldText = "第二次签名";
      reqCAPdf.FieldName = "sig2";

      resCAPdf = CAManager.Instance.CASignPdf(UserInfo, reqCAPdf);
      if (resCAPdf.Code >= 0)
      {
        //Convert.ToByte
        byte[] DocBytes = Convert.FromBase64String(resCAPdf.Data.SignedPDFBase64);
        FileStream fs = new FileStream(reqCAPdf.FilePath + "_signed.pdf", FileMode.Create);
        BinaryWriter bw = new BinaryWriter(fs);
        bw.Write(DocBytes, 0, DocBytes.Length);
        bw.Close();
        fs.Close();
      }


    }

    private void button5_Click(object sender, EventArgs e)
    {
            ReqCALogin reqLogin = new ReqCALogin();
            reqLogin.UserUid = "4238";
            reqLogin.UserPin = "123456";

            UserInfo UserInfo = new UserInfo();

            ResCA<CALoginInfo> resCALogin = CAManager.Instance.CALogin(UserInfo, reqLogin);
            richTextBox1.AppendText(JsonHelper.ToJson(resCALogin)+"\r\n");
            if (resCALogin.Code >= 0)
            {
              ReqCASign reqTxt = new ReqCASign();
              reqTxt.UserToken = resCALogin.Data.UserToken;
              reqTxt.OriginData = "Test";
              reqTxt.UseQ7 = true;
              reqTxt.UseTimestamp = true;
              reqTxt.NeedVerifySign = true;
              reqTxt.IncludeCertOption = 2;
              ResCA<CASign> resTxt1 = CAManager.Instance.CASign(UserInfo, reqTxt);
              richTextBox1.AppendText(JsonHelper.ToJson(resTxt1) + "\r\n");

              reqTxt.UserToken = resCALogin.Data.UserToken;
              reqTxt.OriginData = CryptoHelper.DecodeBase64("utf-8", resTxt1.Data.SignedData);
              reqTxt.UseQ7 = true;
              reqTxt.UseTimestamp = true;
              reqTxt.NeedVerifySign = true;
              reqTxt.IncludeCertOption = 2;
              ResCA<CASign> resTxt2 = CAManager.Instance.CASign(UserInfo, reqTxt);
              richTextBox1.AppendText(JsonHelper.ToJson(resTxt2) + "\r\n");
              

            }



    }




  }


}
